package com.jilijili.exceptions;

import com.jilijili.grace.result.GraceJSONResult;
import com.jilijili.grace.result.ResponseStatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
public class GraceExceptionHandler {

    // 文件传输异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJSONResult returnMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_MAX_SIZE_500KB_ERROR);
    }


    //自定义异常
    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyException(MyCustomException e) {
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }


    // 传输参数校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult resultMethodA(MethodArgumentNotValidException e) {
        BindingResult errorResult = e.getBindingResult();
        Map<String, String> errors = getErrors(errorResult);
        return GraceJSONResult.errorMap(errors);
    }

    public Map<String, String> getErrors(BindingResult errorResult) {
        Map<String, String> errorMap = new HashMap<>();
        // 校验字段的每一项都会出现的错误信息
        List<FieldError> errorList = errorResult.getFieldErrors();

        errorList.forEach(fieldError -> {
            // 到底是那一个字段出现了错误
            String field = fieldError.getField();
            String errorMsg = fieldError.getDefaultMessage();
            errorMap.put(field, errorMsg);
        });
        return errorMap;
    }
}
